package com.gict.antifraudback.controller.web.user;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gict.antifraudback.entity.User;
import com.gict.antifraudback.exception.MyException;
import com.gict.antifraudback.result.ResultEnum;
import com.gict.antifraudback.result.ResultView;
import com.gict.antifraudback.service.UserService;
import com.gict.antifraudback.utils.DESCode;
import com.gict.antifraudback.utils.UserThreadLocal;
import com.gict.antifraudback.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;

/**
 * @author ThinkPad
 */
@RestController
@Slf4j
@RequestMapping("/wapi/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/userInfo")
    public ResultView userInfo() {
        return ResultView.ok(UserThreadLocal.get());
    }

    @GetMapping("/getList")
    public ResultView getList(UserVo userVo) {
        log.info("userVo:{}", userVo);
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(!ObjectUtils.isEmpty(userVo.getName()), User::getName, userVo.getName());
        wrapper.eq(!ObjectUtils.isEmpty(userVo.getUsername()), User::getUsername, userVo.getUsername());
        wrapper.like(!ObjectUtils.isEmpty(userVo.getRoles()), User::getRoles, userVo.getRoles());
        return ResultView.ok(userService.page(new Page<>(userVo.getCurrent(), userVo.getPageSize()), wrapper));
    }

    @GetMapping("/get")
    public ResultView get(@Valid @NotNull Integer id) {
        User user = userService.getById(id);
        if (user == null) {
            throw new MyException("用户不存在");
        }
        user.setPassword("********");
        user.setRolesArray(JSON.parseArray(user.getRoles()));
        return ResultView.ok(user);
    }

    @PostMapping("/delete")
    public ResultView delete(@RequestBody ArrayList<Integer> ids) {
        log.info("userVo:{}", ids);
        for (Integer id : ids) {
            if (id == 1) {
                continue;
            }
            userService.removeById(id);
        }
        return ResultView.okMsg("删除成功");
    }

    @PostMapping("/add")
    public ResultView add(@Valid @RequestBody User user) {
        this.createBefore(user);
        // 设置密码
        user.setPassword(DESCode.encode(user.getPassword()));
        userService.save(user);
        return ResultView.ok();
    }

    /**
     * 创建前检查
     *
     * @param user 用户
     */
    private void createBefore(User user) {
        // 判断是否存在该账号
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(User::getUsername, user.getUsername());
        User exists = userService.getOne(wrapper);

        if (exists != null && !exists.getId().equals(user.getId())) {
            throw new MyException(ResultEnum.CODE_2, "该账号已经存在");
        }
    }

    @PostMapping("/update")
    public ResultView update(@RequestBody @Valid User user) {
        User update = userService.getById(user.getId());
        if (update == null) {
            return ResultView.error(ResultEnum.CODE_2, "数据不存在！");
        }
        user.setPassword(update.getPassword());
        createBefore(user);
        userService.updateById(user);
        return ResultView.ok();
    }

    @PostMapping("/updatePassword")
    public ResultView updatePassword(@RequestBody User user) {
        User update = userService.getById(user.getId());
        if (update == null) {
            return ResultView.error(ResultEnum.CODE_2, "数据不存在！");
        }
        String password = user.getPassword();
        if (ObjectUtils.isEmpty(password)) {
            throw new MyException("密码不能为空");
        }
        update.setPassword(DESCode.encode(password));
        userService.updateById(update);
        return ResultView.ok();
    }

}
